package main

import (
	"net/http"
	"html/template"
	"strings"
)


func serveSave(w http.ResponseWriter, r *http.Request) {
        // check for POST
	if r.Method != "POST" {
                http.Error(w, "Page not found", 404)
		return
	}

	// read form
	name := r.FormValue("name")
	tg := r.FormValue("tags")
	image := r.FormValue("image")
	description := r.FormValue("description")

	// split tags
	var tags []string
	for _, tag := range strings.Split(tg, ",") {
		tags = append(tags, strings.Trim(tag, " "))
	}
	code := recp.newCode()

	// create recipe
	recipe := &Recipe{ name, tags, image, description, code }

	// download
	output, err := downloadResources(recipe)
	type Save struct {
		Title string
		Result string
	}
	var save Save
	if err == nil {
		save = Save{ "Success!", output }
	} else {
		save = Save{ "Failure!", output + "\n" + err.Error() }
	}

	// save recipe
	*recp = append(*recp, *recipe)
	recp.save()

	// load template
	t := template.New("index")
	t, err = t.Parse(save_template)
	if err != nil {
		panic(err)
	}

	err = t.Execute(w, &save)
	if err != nil {
		panic(err)
	}

}


const save_template=`
<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="UTF-8">
    <title>recp - {{ .Title }}</title>
  </head>
  <body>
    <h1>{{ .Title }}</h1>
    <hr>
    <p><a href="/">Voltar para o índice</a></p>
    <p>Resultado:</p>
    <pre>
{{ .Result }}
    </pre>
  </body>
</html>
`
